class Solution {
public:
    vector<int> findKDistantIndices(vector<int>& nums, int key, int k) {

        int n=nums.size();
        vector<int> f(n),b(n);
        int pre=n+k+1;
        for(int i=n-1;i>=0;--i){

            if(nums[i]==key){

                pre=i;
            }
            f[i]=pre;
        }
        pre=-k-1;
        for(int i=0;i<n;++i){

            if(nums[i]==key){

                pre=i;
            }
            b[i]=pre;
        }
        vector<int> ret;
        for(int i=0;i<n;++i){

            if(f[i]-i<=k && f[i]<n && nums[f[i]]==key){

                ret.push_back(i);
            }
            else if(i-b[i]<=k && b[i]>=0 && nums[b[i]]==key){

                ret.push_back(i);
            }
        }

        return ret;
    }
};
